<!--
 * @Author: 张辰龙 zhangchenlong@julimeng.com
 * @Date: 2025-06-23 10:15:49
 * @LastEditors: 张辰龙 zhangchenlong@julimeng.com
 * @LastEditTime: 2025-06-24 13:52:28
 * @FilePath: /zrreportWxMp/pagesTools/selectAddress/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!--地区选择-->
<template>
    <view class="paddingL15" style="padding-top: 30rpx">
        <view class="row topSearchInput">
            <view style="width: 26%; align-items: center" @click="changeCity()">
                <image :src="require('../static/select/dingweixiao.png')"
                    style="width: 26rpx; height: 30rpx; display: inline-block; vertical-align: middle"></image>
                <text class="cityStyle">{{ city }}</text>
                <view style="margin-left: 8rpx; display: inline-block">
                    <image :src="require('../static/select/upDownIcon.png')"
                        style="width: 15rpx; height: 8rpx; vertical-align: middle"></image>
                </view>
            </view>
            <view style="width: 80%">
                <uni-easyinput radius="26" placeholder="请输入要查询的地区" readonly cancelButton="none" cancelText="搜索"
                    v-model="searchVal" @input="searchAddress">
                    <template slot="left">
                        <view style="margin-left: 14rpx; margin-top: 6rpx">
                            <image :src="require('../static/select/sousuo.png')" style="width: 34rpx; height: 34rpx">
                            </image>
                        </view>
                    </template>
                </uni-easyinput>
            </view>
        </view>
        <!--重新定位-->
        <view class="row nowAddress">
            <view @click="hisItemClick(defaultObj)">{{ address }}</view>
            <view class="row" style="width: 150rpx;white-space: nowrap" @click="getLocation">
                <image :src="require('../static/select/dingwei.png')" style="width: 34rpx; height: 34rpx"></image>
                <view class="repAddress">重新定位</view>
            </view>
        </view>
        <!--历史记录-->
        <view v-if="!nearList.length" style="margin-top: 30rpx">
            <view class="row">
                <view class="row" style="justify-content: flex-start">
                    <image :src="require('../static/select/dingweixiao2.png')" style="width: 20rpx; height: 22rpx">
                    </image>
                    <view class="historyStyle">历史记录</view>
                </view>

                <view class="row" v-show="historyList.length">
                    <text @click="clear" v-show="deleteShow"
                        style="padding-top: 10rpx;font-size: 26rpx;white-space: nowrap;margin-right: 20rpx">清空</text>
                    <view class="delete">
                        <image @click="deleteShow = true" :src="require('../static/select/linksc.png')"
                            style="width: 36rpx;height: 36rpx;" v-show="!deleteShow"></image>
                        <text style="color: #2872FD;font-size: 26rpx;white-space: nowrap" v-show="deleteShow"
                            @click="deleteShow = false">完成</text>
                    </view>
                </view>
            </view>
            <!--历史搜索记录-->
            <view class="paddingL15" style="margin-top: 30rpx;">
                <view v-if="showLine > index" @click="hisItemClick(item)" class="historyItem row"
                    v-for="(item, index) in historyList" :key="index">
                    <view class="text-ellipsis" style="">{{ item.name }}</view>
                    <view v-show="deleteShow" @click.stop="closeTag(index)">
                        <image :src="require('../static/select/close.png')" style="width: 24rpx;height: 24rpx"></image>
                    </view>
                </view>
                <view v-if="historyList.length > 5" @click="lookMore" class="row"
                    style="justify-content: flex-start; margin-top: 30rpx">
                    <view class="moreHistory">{{ showHistoryMore ? '收起更多地址' : '展开更多地址' }}</view>
                    <image v-show="!showHistoryMore" :src="require('../static/select/upDownIcon.png')"
                        style="width: 15rpx; height: 8rpx; vertical-align: middle"></image>
                    <image v-show="showHistoryMore" :src="require('../static/select/upTopIcon.png')"
                        style="width: 15rpx; height: 8rpx; vertical-align: middle"></image>
                </view>
            </view>
        </view>
        <!--附近推荐-->
        <view v-if="nearList.length > 0" style="margin-top: 30rpx">
            <!--<view class="row" style="justify-content: flex-start">-->
            <!--  <image src="/pageProduct/static/product/icon/area.png" style="width: 19rpx;height: 22rpx"></image>-->
            <!--  <view class="historyStyle">附近推荐</view>-->
            <!--</view>-->
            <!--历史搜索记录-->
            <view class="paddingL15">
                <view @click="hisItemClick(item)" class="historyItem" v-for="(item, index) in nearList" :key="index">
                    {{ item.name
                    }}</view>
                <!--<view class="row" style="justify-content: flex-start;margin-top: 30rpx">-->
                <!--<view class="moreHistory">{{ nearshowHistoryMore ? '收起更多地址' : '展开更多地址' }}</view>-->
                <!--<image src="/static/shortVideo/upDownIcon.png" style="width: 15rpx;height: 8rpx;vertical-align: middle"></image>-->
                <!--<image src="/static/shortVideo/upTopIcon.png" style="width: 15rpx;height: 8rpx;vertical-align: middle"></image>-->
                <!--</view>-->
            </view>
        </view>

        <uni-popup ref="calcelOrderPop" :maskClick="false" background-color="#fff">
            <view class="popup-content">
                <view class="topContent" style="font-size: 40rpx"></view>
                <view class="cneterContent">您确认是否要删除搜索历史</view>
                <view class="popup-footer">
                    <button class="popup-footer-left" @click="yesStatus">是</button>
                    <button class="popup-footer-right" @click="noStatus">否</button>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import Cache from '@/utils/cache';
import Routine from "@/libs/routine.js";
import residenceTime from "@/mixins/residenceTime";
export default {
    // #ifdef MP-WEIXIN
    options: {
        styleIsolation: 'shared' // 解除样式隔离
    },
    // #endif
    mixins: [residenceTime],
    data() {
        return {
            itemupdata: "",
            timeoutId: null,
            searchVal: '',
            city: '位置',
            where: {
                areaCode: ''
            },
            code: '',
            areaCode: '',
            address: '',
            showLine: 5,
            showHistoryMore: false,
            historyList: [],
            defaultObj: {},
            // nearshowLine: 4,
            // nearshowHistoryMore: false,
            nearList: [],
            deleteShow: false,
            type: '',
        };
    },

    onUnload() {
        uni.$emit('update', { msg: this.itemupdata })
        // 页面卸载时触发，可以看作是返回操作的一部分
    },
    onLoad(opt) {
        this.type = opt.type;
        if (Cache.has('addressSearchList')) {
            this.historyList = JSON.parse(Cache.get('addressSearchList'));
        }
        this.getLocation();
    },
    onShow: function () {
        let _this = this;
        uni.$on('selectCity', function (data) {
            _this.city = data.name;
            _this.address = data.name
            _this.areaCode = data.areaCode;
            uni.$off('selectCity');
        });
    },
    methods: {
         pageViewTrack(stayTime) {
            const route = this.$util.getCurrentRoute()
            let params = {
                Um_Key_SourcePage: route.path,
                Um_Key_Duration: stayTime,
            }
            this.$umaTrack.pageViewTrack(params)
        },
        getAddressInfo(lon, lat) {
            let that = this;
            uni.request({
                url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
                method: 'GET',
                data: {
                    key: '329b1e97a844a0cf2be6e3046a5632cc',
                    location: `${lon}, ${lat}`
                },
                success: async (data) => {
                    const code = that.getCityCode(data.data.regeocode.addressComponent.adcode);
                    const cityStr = data.data.regeocode.addressComponent;
                    // cityStr.province
                    that.city = cityStr.city.length ? cityStr.city.substring(0, 2) : cityStr.province.substring(0, 2);
                    that.code = code;
                    that.address = data.data.regeocode.formatted_address;
                    that.defaultObj = {
                        location: `${lon}, ${lat}`,
                        name: that.address
                    }
                },
                fail(err) {
                    console.log(err);
                }
            });
        },
        getLocation(num) {
            Routine.gettLocation().then(async res => {
                await this.getAddressInfo(res.longitude, res.latitude)
            })
        },
        getCityCode(districtCode) {
            if (typeof districtCode !== 'string' || districtCode.length !== 6) {
                return null; // 如果输入的不是有效的6位字符串代码，返回null或者其他错误处理
            }
            // 提取前四位，然后加上 '00'
            let cityCode = districtCode.substring(0, 4) + '00';
            return cityCode;
        },
        lookMore() {
            this.showHistoryMore = !this.showHistoryMore;
            if (this.showHistoryMore) {
                this.showLine = this.historyList.length;
            } else {
                this.showLine = 5;
            }
        },
        changeCity() {
            uni.navigateTo({ url: '/pagesTools/selectCityList/index' });
        },
        hisItemClick(item) {
            this.itemupdata = item
            this.searchVal = item.name;
            this.address = item.name;
            this.setHistory(item)
            uni.$emit('updateAddress', { msg: this.itemupdata, type: true })
            uni.navigateBack({ delta: 1 });
        },
        closeTag(i) {
            let arr = []
            arr = arr.concat(JSON.parse(Cache.get('addressSearchList')))
            const uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
            let uni = uniqueArr.filter(v => v.name !== '')
            uni.splice(i, 1)
            if (uni.length > 20) {
                uni.pop()
            }
            Cache.set('addressSearchList', uni)
            this.historyList = JSON.parse(Cache.get('addressSearchList'))
            if (this.historyList.length == 0) { this.deleteShow = false }
        },
        clear() {
            this.$refs.calcelOrderPop.open('center')
        },
        yesStatus() {
            Cache.set('addressSearchList', [])
            this.$refs.calcelOrderPop.close()
            this.historyList = []
            this.deleteShow = false
        },
        noStatus() {
            this.$refs.calcelOrderPop.close()
        },
        setHistory(item) {
            // 调用成功之后搜索历史保存到本地
            let arr = [];
            arr.push(item);
            if (!Cache.has('addressSearchList')) {
                Cache.set('addressSearchList', arr);
            } else {
                arr = arr.concat(JSON.parse(Cache.get('addressSearchList')));
                const uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
                let uni = uniqueArr.filter((v) => v.name !== '');
                if (uni.length > 20) {
                    uni.pop();
                }
                Cache.set('addressSearchList', uni);
                this.historyList = JSON.parse(Cache.get('addressSearchList'));
            }
        },
        searchAddress(val) {
            this.searchVal = val;
            clearTimeout(this.timeoutId);
            // 设置新的定时器
            this.timeoutId = setTimeout(() => {
                this.getAddress();

                // this.followingGET();  // 发起请求
            }, 500); // 设置防抖的延迟时间（1秒）
        },
        getAddress() {
            let params = {
                address: this.searchVal
            };

            // 接口调用
            this.searchLocation(this.searchVal)
                .then((results) => {
                    this.nearList = results.tips
                })
                .catch((error) => {
                    console.error(error);
                });
        },
        searchLocation(query) {
            const AMAP_KEY = '329b1e97a844a0cf2be6e3046a5632cc';
            return new Promise((resolve, reject) => {
                uni.request({

                    //https://restapi.amap.com/v3/assistant/inputtips?parameters
                    url: `https://restapi.amap.com/v3/assistant/inputtips?key=${AMAP_KEY}&city=${this.areaCode || this.code}&children=1&offset=1&page=1&extensions=all&keywords=${encodeURIComponent(query)}`,
                    method: 'GET',
                    success: (res) => {
                        console.log("res", res)
                        if (res.statusCode == 200) {
                            resolve(res.data);
                        } else {
                            reject(new Error('搜索位置失败'));
                        }
                    },
                    fail: (err) => {
                        reject(err);
                    }
                });
            });
        }
        // nearlookMore() {
        //   this.nearshowHistoryMore = !this.nearshowHistoryMore
        //   if (this.nearshowHistoryMore) {
        //     this.nearshowLine = this.nearList.length
        //   } else {
        //     this.nearshowLine = 4
        //   }
        // }
    }
};
</script>

<style lang="scss">
page {
    background: #ffffff !important;
}

.text-ellipsis {
    font-size: 32rpx;
    width: 500rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.topSearchInput {
    background: #ffffff;
    position: sticky;
    top: 0;
    z-index: 99;

    .cityStyle {
        margin-left: 8rpx;
        display: inline-block;
        width: 86rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        vertical-align: middle;
        text-align: center;
    }

    /deep/ .is-input-border {
        border: none;
    }

    /deep/ .uni-easyinput__content {
        background-color: #f5f5f5 !important;
    }
}

.nowAddress {
    margin-top: 24rpx;
    padding-bottom: 27rpx;
    border-bottom: 2rpx solid #ededed;
    color: #333333;
    font-size: 30rpx;

    .repAddress {
        color: #fa7700;
        font-size: 28rpx;
    }
}

.historyStyle {
    color: #666666;
    font-size: 28rpx;
    margin-left: 6rpx;
}

.historyItem {
    font-weight: 500;
    color: #333333;
    font-size: 32rpx;
    height: 100rpx;
    line-height: 100rpx;
    border-bottom: 2rpx solid #ededed;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    align-items: center;
}

.moreHistory {
    color: #666666;
    font-size: 30rpx;
    margin-right: 10rpx;
}

.delete {
    width: 80rpx;
    height: 48rpx;
    border-left: 2rpx solid #E6E6E6;
    padding-left: 20rpx;
    padding-top: 10rpx;
}

.popup-content {
    width: 620rpx;
    height: 460rpx;
    border-radius: 32rpx;
    background-color: #fff;

    .topContent {
        text-align: center;
        color: #111111;
        font-size: 40rpx;
        padding-top: 50rpx;
    }

    .cneterContent {
        text-align: center;
        margin-top: 64rpx;
        margin-bottom: 124rpx;
        color: #666666;
        font-size: 32rpx;
    }

    .popup-footer {
        display: flex;
        justify-self: center;

        .popup-footer-left {
            color: #2872fd;
            width: 256rpx;
            background-color: white;
            border: 1px solid #0f62fe;
            border-radius: 80rpx;
            margin-right: 30rpx;
        }

        .popup-footer-right {
            color: white;
            width: 256rpx;
            background-color: #0f62fe;
            border-radius: 80rpx;
        }
    }
}

/deep/ .uni-popup .uni-popup__wrapper {
    border-radius: 32rpx;
}
</style>
